// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <string>

#include <pollux/core/plan_node.h>
#include <pollux/testing/exec/result_verifier.h>
#include <pollux/testing/exec/util/assert_query_builder.h>
#include <pollux/plan/plan_builder.h>
#include <pollux/vector/complex_vector.h>

namespace kumo::pollux::exec::test {

// Applies specified SQL transformation to the results before comparing. For
// example, sorts an array before comparing results of array_agg.
//
// Supports 'compare' API.
class TransformResultVerifier : public ResultVerifier {
 public:
  // @param transform fmt::format-compatible SQL expression to use to transform
  // aggregation results before comparison. The string must have a single
  // placeholder for the column name that contains aggregation results. For
  // example, "array_sort({})".
  explicit TransformResultVerifier(const std::string& transform)
      : transform_{transform} {}

  static std::shared_ptr<ResultVerifier> create(const std::string& transform) {
    return std::make_shared<TransformResultVerifier>(transform);
  }

  bool supportsCompare() override {
    return true;
  }

  bool supportsVerify() override {
    return false;
  }

  void initialize(
      const std::vector<RowVectorPtr>& /*input*/,
      const std::vector<std::string>& groupingKeys,
      const core::AggregationNode::Aggregate& /*aggregate*/,
      const std::string& aggregateName) override {
    projections_ = groupingKeys;
    projections_.push_back(
        fmt::format(fmt::runtime(transform_), aggregateName));
  }

  bool compare(const RowVectorPtr& result, const RowVectorPtr& altResult)
      override {
    return assertEqualResults({transform(result)}, {transform(altResult)});
  }

  bool verify(const RowVectorPtr& /*result*/) override {
    POLLUX_UNSUPPORTED();
  }

  void reset() override {
    projections_.clear();
  }

 private:
  RowVectorPtr transform(const RowVectorPtr& data) {
    POLLUX_CHECK(!projections_.empty());
    auto plan = PlanBuilder().values({data}).project(projections_).planNode();
    return AssertQueryBuilder(plan).copyResults(data->pool());
  }

  const std::string transform_;

  std::vector<std::string> projections_;
};

} // namespace kumo::pollux::exec::test
